﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.DinnerOrder;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class DinnerOrderController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DinnerOrderController));
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有点餐订单，只显示点餐成功的订单
        /// </summary>
        /// <param name="type">current - 15内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            List<DinnerOrder> orders;

            if (type == "current")
            {
                orders =
                    _ctx.DinnerOrders.Where(x => x.OpenId == azUser.OpenId).IsStatus(DinnerExtensions.OrderStatus.落单成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 15)
                        .OrderByDescending(x => x.DinnerDate).ThenByDescending(x => x.CreateTime).ToList();
            }
            else
            {
                orders =
                    _ctx.DinnerOrders.Where(x => x.OpenId == azUser.OpenId).IsStatus(DinnerExtensions.OrderStatus.落单成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 15)
                        .OrderByDescending(x => x.DinnerDate).ThenByDescending(x => x.CreateTime).ToList();
            }

            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Orders = orders.Select(x => new GetOrderListResponse.Order
                {
                    OrderId = x.Id,
                    CardNo = x.CardNo,
                    CardName = x.CardName,
                    OrderNo = x.OrderNo,
                    CreateDt = x.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                    Date = x.DinnerDate,
                    FpName = x.FpName,
                    HmtName = x.HmtName,
                    FoodCnt = x.FoodCount.ToString(),
                    TotalMoney = x.TotalMoney.GetValueOrDefault().ToString("F2")
                }).ToList()
            };
        }

        /// <summary>
        /// 获取点餐订单详情
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetail")]
        public GetOrderDetailResponse GetOrderDetail(int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var order = _ctx.DinnerOrders.IsStatus(DinnerExtensions.OrderStatus.落单成功)
                .FirstOrDefault(x => x.OpenId == azUser.OpenId && x.Id == orderId);
            if (order == null)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };
            }

            var foods = _ctx.DinnerOrderItems.Where(x => x.OrderId == order.Id).ToList();
            
            bool canUnDinner = 
                string.CompareOrdinal(order.DinnerDate + " " + order.HmtEndTime, DateTime.Today.ToString("yyyy-MM-dd")) > 0;

            return new GetOrderDetailResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                OrderId = order.Id,
                OrderNo = order.OrderNo,
                CardNo = order.CardNo,
                CardName = order.CardName,
                CreateDt = order.CreateTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm"),
                CanUnDinner = canUnDinner,
                Date = order.DinnerDate,
                FpName = order.FpName,
                HmtName = order.HmtName,
                FoodCnt = order.FoodCount.ToString(),
                TotalMoney = order.TotalMoney.GetValueOrDefault().ToString("F2"),
                Foods = foods.Select(x=> new GetOrderDetailResponse.Food
                {
                    FoodName = x.FoodName,
                    UnitPrice = x.FoodUnitPrice.GetValueOrDefault().ToString("F2"),
                    Cnt = x.FoodCount.GetValueOrDefault().ToString(),
                    Price = x.FoodAmount.GetValueOrDefault().ToString("F2")
                }).ToList()
            };
        }
    }
}
